import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _isEmpty from "lodash/isEmpty";
import _isArray from "lodash/isArray";
import _isFunction from "lodash/isFunction";

var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _dec10, _class, _class2;

/**
 * 数据权限维度动态渲染 - 增加数据弹框
 * @date: 2019-9-11
 */
import React from 'react';
import { Button, Form, Input, Modal, Table, notification, Row, Col } from 'antd';
import { Bind } from 'lodash-decorators';
import qs from 'querystring';
import intl from 'utils/intl';
import { tableScrollWidth, getCurrentOrganizationId, getResponse, createPagination } from 'utils/utils';
import { SEARCH_FORM_ITEM_LAYOUT } from 'utils/constants';
import { queryLovData } from 'services/api';
var formItemLayout = {
  labelCol: {
    sm: {
      span: 8
    }
  },
  wrapperCol: {
    sm: {
      span: 14
    }
  }
}; // /**
//  * 使用 Form.Item 组件
//  */
// const FormItem = Form.Item;

var EditForm = (_dec = Form.create({
  fieldNameProp: null
}), _dec2 = Bind(), _dec3 = Bind(), _dec4 = Bind(), _dec5 = Bind(), _dec6 = Bind(), _dec7 = Bind(), _dec8 = Bind(), _dec9 = Bind(), _dec10 = Bind(), _dec(_class = (_class2 = /*#__PURE__*/function (_React$Component) {
  _inherits(EditForm, _React$Component);

  var _super = _createSuper(EditForm);

  function EditForm(props) {
    var _this;

    _classCallCheck(this, EditForm);

    _this = _super.call(this, props);
    _this.state = {
      addRows: [],
      dataSource: [],
      addTrueRows: [],
      treeKeys: [],
      pagination: {},
      loading: true,
      flag: true
    };
    return _this;
  } // eslint-disable-next-line


  _createClass(EditForm, [{
    key: "UNSAFE_componentWillReceiveProps",
    value: function UNSAFE_componentWillReceiveProps(nextProps) {
      var modalVisible = nextProps.modalVisible,
          lov = nextProps.lov;

      if (modalVisible && this.state.flag && !_isEmpty(lov)) {
        this.queryValue();
        this.setState({
          flag: false
        });
      }
    }
    /**
     * 点击确定触发事件
     */

  }, {
    key: "okHandle",
    value: function okHandle() {
      var _this$props = this.props,
          addData = _this$props.addData,
          tenantId = _this$props.tenantId;
      var addTrueRows = this.state.addTrueRows;

      if (!_isEmpty(addTrueRows)) {
        if (tenantId !== undefined) {
          var arr = addTrueRows.map(function (item) {
            return _objectSpread({
              tenantId: tenantId
            }, item);
          });
          addData(arr);
        } else {
          var _arr = addTrueRows;
          addData(_arr);
        }

        this.setState({
          flag: true,
          addRows: [],
          addTrueRows: []
        });
      } else {
        notification.warning({
          message: intl.get('cpaas.common.message.confirm.selected.atLeast').d('请至少选择一行数据')
        });
      }
    }
    /**
     * 点击取消触发事件
     */

  }, {
    key: "cancelHandle",
    value: function cancelHandle() {
      var onHideAddModal = this.props.onHideAddModal;

      if (onHideAddModal) {
        this.setState({
          flag: true,
          addRows: [],
          addTrueRows: []
        });
        onHideAddModal(false);
      }
    }
    /**
     *分页change事件
     */

  }, {
    key: "handleTableChange",
    value: function handleTableChange() {
      var pagination = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      this.queryValue(pagination);
    }
    /**
     * 表格勾选
     * @param {null} _ 占位
     * @param {object} selectedRow 选中行
     */

  }, {
    key: "onSelectChange",
    value: function onSelectChange(selectedRowKeys, selectedRow) {
      var _this$props2 = this.props,
          defaultFlag = _this$props2.defaultFlag,
          _this$props2$lov = _this$props2.lov,
          valueField = _this$props2$lov.valueField,
          displayField = _this$props2$lov.displayField;
      var addRows = this.state.addRows;
      var newSelectedRow = addRows;
      var addTrueRows = [];
      var arr = [];
      newSelectedRow = newSelectedRow.filter(function (temp) {
        return selectedRowKeys.includes(temp[valueField]);
      });
      newSelectedRow = [].concat(_toConsumableArray(newSelectedRow), _toConsumableArray(selectedRow)).filter(function (item) {
        if (arr.includes(item[valueField])) {
          return false;
        } else {
          arr.push(item[valueField]);
          return true;
        }
      });

      if (defaultFlag) {
        addTrueRows = newSelectedRow;
      } else {
        addTrueRows = newSelectedRow.map(function (item) {
          return {
            dataId: item[valueField],
            dataName: item[displayField],
            dataCode: item.tenantName
          };
        });
      }

      this.setState({
        addRows: newSelectedRow,
        addTrueRows: addTrueRows
      });
    }
    /**
     * 表单重置
     */

  }, {
    key: "handleFormReset",
    value: function handleFormReset() {
      var form = this.props.form;
      form.resetFields();
    }
    /**
     * 树 child 属性更改
     * @param {Array} list 原树结构数据
     * @param {String} childName 要替换的 childName
     */

  }, {
    key: "setChildren",
    value: function setChildren(data, childName) {
      var _this2 = this;

      return childName ? data.map(function (n) {
        var item = n;

        if (!_isEmpty(n[childName])) {
          _this2.defineProperty(item, 'children', [_objectSpread({}, n[childName])]);
        }

        if (!_isEmpty(item.children)) {
          item.children = _this2.setChildren(item.children);
        }

        return item;
      }) : data;
    }
    /**
     * 处理返回列表数据
     * @param {Object|Array} data - 返回的列表数据
     */

  }, {
    key: "dataFilter",
    value: function dataFilter(data) {
      var _this$props$lov = this.props.lov,
          _this$props$lov$value = _this$props$lov.valueField,
          rowkey = _this$props$lov$value === void 0 ? 'lovId' : _this$props$lov$value,
          childrenFieldName = _this$props$lov.childrenFieldName;

      var isTree = _isArray(data);

      var hasParams = !_isEmpty(Object.values(this.props.form.getFieldsValue()).filter(function (e) {
        return e !== undefined && e !== '';
      }));
      var list = isTree ? this.setChildren(data, childrenFieldName) : data.content;
      var pagination = !isTree && createPagination(data);
      var treeKeys = []; // 树状 key 列表

      if (isTree && hasParams) {
        /**
         * 遍历生成树列表
         * @param {*} treeList - 树列表数据
         */
        var flatKeys = function flatKeys(treeList) {
          if (_isArray(treeList.children) && !_isEmpty(treeList.children)) {
            treeKeys.push(treeList[rowkey]);
            treeList.children.forEach(function (item) {
              return flatKeys(item);
            });
          } else {
            treeKeys.push(treeList[rowkey]);
          }
        };

        list.forEach(function (item) {
          return flatKeys(item);
        }); // 遍历生成 key 列表
      }

      this.setState({
        dataSource: list,
        treeKeys: treeKeys,
        pagination: pagination
      });
    }
    /**
     * 查询方法
     */

  }, {
    key: "queryValue",
    value: function queryValue() {
      var _this3 = this;

      var pagination = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      this.setState({
        loading: true
      });
      var filter = this.props.form.getFieldsValue();
      var _this$props$lov2 = this.props.lov,
          queryUrl = _this$props$lov2.queryUrl,
          pageSize = _this$props$lov2.pageSize,
          lovCode = _this$props$lov2.lovCode,
          lovTypeCode = _this$props$lov2.lovTypeCode;
      var _this$props$queryPara = this.props.queryParams,
          queryParams = _this$props$queryPara === void 0 ? {} : _this$props$queryPara;
      var nowQueryParams = queryParams || {};

      if (_isFunction(nowQueryParams)) {
        nowQueryParams = nowQueryParams();
      }

      var queryIndex = queryUrl.indexOf('?');
      var sourceQueryParams = {};

      if (queryIndex !== -1) {
        sourceQueryParams = qs.parse(queryUrl.substr(queryIndex + 1));
      }

      var sourceParams = _objectSpread(_objectSpread(_objectSpread({}, filter), {}, {
        page: pagination.current - 1 || 0,
        size: pagination.pageSize || pageSize || 10
      }, sourceQueryParams), nowQueryParams);

      var params = lovTypeCode !== 'URL' ? Object.assign(sourceParams, {
        lovCode: lovCode
      }) : sourceParams;
      /**
       * 替换查询 Url 中的变量
       * @param {String} url
       * @param {Object} data
       */

      function getUrl(url, data) {
        var ret = url;
        var organizationRe = /\{organizationId\}|\{tenantId\}/g;
        Object.keys(data).map(function (key) {
          var re = new RegExp("{".concat(key, "}"), 'g');
          ret = ret.replace(re, data[key]);
          return ret;
        });

        if (organizationRe.test(ret)) {
          ret = ret.replace(organizationRe, getCurrentOrganizationId());
        }

        var index = ret.indexOf('?'); // 查找是否有查询条件

        if (queryIndex !== -1) {
          ret = ret.substr(0, index);
        }

        return ret;
      }

      var url = getUrl(queryUrl, queryParams);
      queryLovData(url, params).then(function (res) {
        if (getResponse(res)) {
          _this3.dataFilter(res);
        }
      }).finally(function () {
        _this3.setState({
          loading: false
        });
      });
    }
  }, {
    key: "renderForm",
    value: function renderForm() {
      var _this$props$lov3 = this.props.lov;
      _this$props$lov3 = _this$props$lov3 === void 0 ? {} : _this$props$lov3;
      var _this$props$lov3$quer = _this$props$lov3.queryFields,
          queryFields = _this$props$lov3$quer === void 0 ? [] : _this$props$lov3$quer;
      var getFieldDecorator = this.props.form.getFieldDecorator;
      return /*#__PURE__*/React.createElement(Form, null, /*#__PURE__*/React.createElement("div", {
        style: {
          display: 'flex',
          marginBottom: '10px',
          alignItems: 'flex-start'
        }
      }, /*#__PURE__*/React.createElement(Row, {
        type: "flex",
        align: "bottom",
        gutter: 16
      }, queryFields && queryFields.map(function (queryItem) {
        return /*#__PURE__*/React.createElement(Col, {
          span: 12
        }, /*#__PURE__*/React.createElement(Form.Item, Object.assign({}, SEARCH_FORM_ITEM_LAYOUT, {
          label: queryItem.label
        }, formItemLayout, {
          key: queryItem.field
        }), getFieldDecorator(queryItem.field)( /*#__PURE__*/React.createElement(Input, null))));
      })), /*#__PURE__*/React.createElement("div", {
        style: {
          display: 'flex',
          flexShrink: 0,
          alignItems: 'center',
          height: '40px'
        }
      }, /*#__PURE__*/React.createElement(Button, {
        style: {
          marginRight: 8
        },
        onClick: this.handleFormReset
      }, intl.get('cpaas.common.button.reset').d('重置')), /*#__PURE__*/React.createElement(Button, {
        type: "primary",
        htmlType: "submit",
        onClick: this.queryValue
      }, intl.get('cpaas.common.button.search').d('查询')))));
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props3 = this.props,
          modalVisible = _this$props3.modalVisible,
          confirmLoading = _this$props3.confirmLoading,
          _this$props3$lov = _this$props3.lov;
      _this$props3$lov = _this$props3$lov === void 0 ? {} : _this$props3$lov;
      var title = _this$props3$lov.title,
          _this$props3$lov$tabl = _this$props3$lov.tableFields,
          tableFields = _this$props3$lov$tabl === void 0 ? [] : _this$props3$lov$tabl,
          _this$props3$lov$valu = _this$props3$lov.valueField,
          rowKey = _this$props3$lov$valu === void 0 ? '' : _this$props3$lov$valu;
      var _this$state = this.state,
          addRows = _this$state.addRows,
          _this$state$dataSourc = _this$state.dataSource,
          dataSource = _this$state$dataSourc === void 0 ? [] : _this$state$dataSourc,
          _this$state$paginatio = _this$state.pagination,
          pagination = _this$state$paginatio === void 0 ? {} : _this$state$paginatio,
          treeKeys = _this$state.treeKeys,
          loading = _this$state.loading;
      var rowSelection = {
        onChange: this.onSelectChange,
        selectedRowKeys: addRows.map(function (n) {
          return n[rowKey];
        })
      };
      var treeProps = _isArray(dataSource) ? {
        uncontrolled: true,
        expandedRowKeys: treeKeys
      } : {};
      return /*#__PURE__*/React.createElement(Modal, {
        destroyOnClose: true,
        title: title,
        visible: modalVisible,
        confirmLoading: confirmLoading,
        width: 900,
        onOk: this.okHandle,
        onCancel: this.cancelHandle
      }, /*#__PURE__*/React.createElement("div", {
        className: "table-list-search"
      }, this.renderForm()), /*#__PURE__*/React.createElement(Table, Object.assign({
        bordered: true,
        rowKey: rowKey,
        columns: tableFields,
        scroll: {
          x: tableScrollWidth(tableFields)
        },
        loading: loading,
        dataSource: dataSource,
        rowSelection: rowSelection,
        pagination: pagination,
        onChange: this.handleTableChange
      }, treeProps)));
    }
  }]);

  return EditForm;
}(React.Component), (_applyDecoratedDescriptor(_class2.prototype, "okHandle", [_dec2], Object.getOwnPropertyDescriptor(_class2.prototype, "okHandle"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "cancelHandle", [_dec3], Object.getOwnPropertyDescriptor(_class2.prototype, "cancelHandle"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleTableChange", [_dec4], Object.getOwnPropertyDescriptor(_class2.prototype, "handleTableChange"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "onSelectChange", [_dec5], Object.getOwnPropertyDescriptor(_class2.prototype, "onSelectChange"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleFormReset", [_dec6], Object.getOwnPropertyDescriptor(_class2.prototype, "handleFormReset"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "setChildren", [_dec7], Object.getOwnPropertyDescriptor(_class2.prototype, "setChildren"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "dataFilter", [_dec8], Object.getOwnPropertyDescriptor(_class2.prototype, "dataFilter"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "queryValue", [_dec9], Object.getOwnPropertyDescriptor(_class2.prototype, "queryValue"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "renderForm", [_dec10], Object.getOwnPropertyDescriptor(_class2.prototype, "renderForm"), _class2.prototype)), _class2)) || _class);
export { EditForm as default };